El paquete Matplotlib ofrece un conjunto de herramientas para generar gráficos en Python. Aunque existen muchos paquetes de este tipo en Python Matplotlib es el más popular. Debido a esa misma popularidad que tiene el paquete generalmente ya viene instalado, aún así, en caso contrario podemos instalarlo de la siguiente manera:

pip install Matplotlib

Intrucción para instalar Matplotlib.

import matplotlib as mpl
import matplotlib.pyplot as plt

Para observar las partes del gráfico vamos a utilizar los siguientes datos de ejemplo:

x, y = [1, 2, 3, 4], [1, 4, 2, 3]

Podemos verlo como el contenedor completo de la figura o gráfico. Aquí se van a almacenar cada uno de los ejes, elementos especiales como los títulos y las leyendas, así como también otras figuras.

fig, ax = plt.subplots()
plt.show()

El Axes es un Artist que se añade a la Figura. Es aquí donde se define el gráfico a dibujar y generalmente esta asociado a 2 objetos Axis, aunque podrían ser 3 (para gráficos en 3D). Se puede definir, ademas del gráfico, elementos como el título, la etiqueta del eje x, la etiqueta del eje y, etc.

fig, ax = plt.subplots()

ax.plot(x, y)
no_print = ax.set_title("Este es el título")
no_print = ax.set_xlabel("Este es el eje X")
no_print = ax.set_ylabel("Este es el eje Y")

plt.show()

Los objetos Axis definen la escala, los limites del gráfico, los ticks y los tickslabels.

fig, ax = plt.subplots()

ax.plot(x, y)
no_print = ax.set_title("Este es el título")
no_print = ax.set_xlabel("Este es el eje X")
no_print = ax.set_ylabel("Este es el eje Y")

no_print = ax.set_xlim(0, 10)
no_print = ax.set_xticks(range(0, 11, 2), ['A', 'B', 'C', 'D', 'E', 'F'], rotation = 20)
#ax.set_xticklabels(['A', 'B', 'C', 'D', 'E', 'F'])

no_print = ax.set_ylim(-3, 5)
no_print = ax.set_yticks([0, 1, 2, 3])

plt.show()

Se refiere a todo lo visible en el gráfico o figura.

fig, ax = plt.subplots()

ax.plot(x, y)
no_print = ax.set_title("Este es el título")
no_print = ax.set_xlabel("Este es el eje X")
no_print = ax.set_ylabel("Este es el eje Y")

no_print = ax.set_xlim(0, 10)
no_print = ax.set_xticks(range(0, 11, 2), ['A', 'B', 'C', 'D', 'E', 'F'], rotation = 20)
no_print = ax.set_xticklabels(['A1', 'B2', 'C3', 'D4', 'E5', 'F6'])

no_print = ax.set_ylim(-3, 5)
no_print = ax.set_yticks([0, 1, 2, 3])

plt.show()

Este es el tipo de gráfico más básico, en el caso de Matplotlib basta con utilizar el método plot.

x, y = [1, 2, 3, 4], [1, 4, 2, 3]

fig, ax = plt.subplots()

ax.plot(x, y)

plt.show()
Definir color de la línea
x = [0, 4]

fig, ax = plt.subplots()

ax.plot(x, [3, 3], color = "red")
ax.plot(x, [2, 2], color = "palegreen")
ax.plot(x, [1, 1], color = "#ab6100")

plt.show()
Definir tipo de la línea
x = [0, 4]

fig, ax = plt.subplots()

ax.plot(x, [16, 16], linestyle = "solid")
ax.plot(x, [15, 15], linestyle = "-")

ax.plot(x, [13, 13], linestyle = "dashed")
ax.plot(x, [12, 12], linestyle = "--")

ax.plot(x, [10, 10], linestyle = "dashdot")
ax.plot(x, [9,  9], linestyle = "-.")

ax.plot(x, [7, 7], linestyle = "dotted")
ax.plot(x, [6, 6], linestyle = ":")

ax.plot(x, [4, 4], "-o")

plt.show()
Definir estilo de la línea
x = [0, 4]

fig, ax = plt.subplots()

ax.plot(x, [2, 2], linestyle = "solid")
ax.plot(x, [1, 1], linestyle = "solid", color='red', linewidth=10)

plt.show()

También conocido como scatter, para ello debemos llamar al método scatter.

x, y = [1, 2, 3, 4], [1, 4, 2, 3]

fig, ax = plt.subplots()

ax.scatter(x, y)

plt.show()
Definir forma del punto
x = [0, 4]

fig, ax = plt.subplots()

ax.scatter(x, [11, 11], marker = "o")
ax.scatter(x, [10, 10], marker = ".")
ax.scatter(x, [9, 9],   marker = ",")
ax.scatter(x, [8, 8],   marker = "x")
ax.scatter(x, [7, 7],   marker = "+")
ax.scatter(x, [6, 6],   marker = "v")
ax.scatter(x, [5, 5],   marker = "^")
ax.scatter(x, [4, 4],   marker = "<")
ax.scatter(x, [3, 3],   marker = ">")
ax.scatter(x, [2, 2],   marker = "s")
ax.scatter(x, [1, 1],   marker = "d")

plt.show()
Definir estilo del punto
x = [0, 4]

fig, ax = plt.subplots()

ax.scatter(x, [2, 2], marker = "o")
ax.scatter(x, [1, 1], marker = "o", c = "red", s = 200)

plt.show()
Escala de color y tamaño

Para este ejemplo se utiliza la tabla iris donde se grafican los puntos según el largo y el ancho del sepalo, luego el tamaño se define según el valor del ancho del petalo y el color según el largo del petalo.

import pandas as pd

iris = pd.read_csv("../../../datos/iris_v1.csv", sep = ";")

fig, ax = plt.subplots()

scatter = ax.scatter(iris.s_largo, iris.s_ancho, marker = "d", alpha = 0.4, 
           s = iris.p_ancho * 200, c = iris.p_largo, cmap = 'viridis')
no_print = fig.colorbar(scatter, ax = ax)
plt.show()

Para este ejemplo se utiliza la tabla iris donde se grafican los puntos según el largo y el ancho del sepalo, luego el tamaño se define según el valor del ancho del petalo y el color según la especie.

color = [0 if x == "setosa" else 1 if x == "versicolor" else 2 for x in iris.tipo.to_list()]

fig = plt.figure()
fig, ax = plt.subplots()

scatter = ax.scatter(iris.s_largo, iris.s_ancho, marker = "d", alpha = 0.4, 
           s = iris.p_ancho * 200, c = color, cmap = 'plasma')
fig.legend(handles = scatter.legend_elements()[0], 
           labels = ["setosa", "versicolor", "virginica"], title = "Especie")
plt.show()
<Figure size 768x480 with 0 Axes>

Para los gráficos de barra contamos con 2 instrucciones: bar para graficar de forma vertical y barh para graficar de forma horizontal.

Vertical
x = ["A", "B", "C", "D", "E"]
y = [2, 5, 2, 1, 4]

fig, ax = plt.subplots()

no_print = ax.bar(x, y, width = 1, edgecolor = "white", linewidth = 1.5)

plt.show()
Horizontal
x = ["A", "B", "C", "D", "E"]
y = [2, 5, 2, 1, 4]

fig, ax = plt.subplots()

no_print = ax.barh(x, y, height = 1, edgecolor = "white", linewidth = 1.5)

plt.show()
Estilo de la barra
import numpy as np

x = ["A", "B", "C", "D", "E"]
y = [2, 5, 2, 1, 4]

fig, ax = plt.subplots()

bar1 = ax.bar(x, y, width = 1, edgecolor = "white", linewidth = 1.5, color = "pink")

no_print = ax.bar_label(bar1, padding = 3) # Agregar texto del valor

plt.show()
Agrupar
import numpy as np

etq = ["A", "B", "C", "D", "E"]
x = np.arange(len(etq))
grupo_1 = [2, 5, 2, 1, 4]
grupo_2 = [3, 3, 4, 1, 2]
grupo_3 = [1, 2, 4, 2, 5]

width = 0.25

fig, ax = plt.subplots()

ax.bar(x - width, grupo_1, width = width, edgecolor = "white", linewidth = 1.5)
ax.bar(x, grupo_2, width = width, edgecolor = "white", linewidth = 1.5)
ax.bar(x + width, grupo_3, width = width, edgecolor = "white", linewidth = 1.5)
ax.set_xticks(x, etq)

plt.show()

Para un histograma utilizaremos la función hist.

y = [2, 5, 2, 1, 4, 2, 3, 1, 2, 3, 4, 5, 2, 2, 4, 3, 4, 2, 1, 4]

fig, ax = plt.subplots()
no_print = ax.hist(y, bins = 4, linewidth = 0.5, edgecolor = "white", color = "darkgreen")
plt.show()

Para un Boxplot utilizaremos la función boxplot.

y = [2, 5, 2, 1, 4, 2, 3, 1, 2, 3, 4, 5, 2, 2, 4, 3, 4, 2, 12, 4]

fig, ax = plt.subplots()
no_print = ax.boxplot(y, widths = 0.5, patch_artist = True,
           flierprops = {'marker': 'x', 'markersize': 10, 'markeredgecolor': 'darkred'}, # Estilo del punto
           medianprops = {"color": "white", "linewidth": 2}, # Estilo de la línea del promedio
           boxprops = {"facecolor": "darkblue", "edgecolor": "white", "linewidth": 0.5}, # Estilo de la caja
           whiskerprops = {"color": "darkblue", "linewidth": 1.5}, # Estilo de las líneas verticales
           capprops={"color": "darkblue", "linewidth": 1.5} # Estilo de las líneas horizontales
          )
plt.show()

Se puede pasar un data.frame, este debe contener solo variables numéricas.

aux = iris.drop(columns = ["tipo"])

fig, ax = plt.subplots()
no_print = ax.boxplot(aux, widths = 0.5, patch_artist = True,
           flierprops = {'marker': 'x', 'markersize': 10, 'markeredgecolor': 'darkred'}, # Estilo del punto
           medianprops = {"color": "white", "linewidth": 2}, # Estilo de la línea del promedio
           boxprops = {"facecolor": "darkblue", "edgecolor": "white", "linewidth": 0.5}, # Estilo de la caja
           whiskerprops = {"color": "darkblue", "linewidth": 1.5}, # Estilo de las líneas verticales
           capprops={"color": "darkblue", "linewidth": 1.5} # Estilo de las líneas horizontales
          )
ax.set_xticks(range(1, 5), aux.columns)
plt.show()

Para realizar el gráfico circular, también conocido como pie o pastel, vamos a utilizar la función pie.

x = ["A", "B", "C", "D"]
y = [1, 2, 3, 4]

# plot
fig, ax = plt.subplots()
no_print = ax.pie(y,
       labels = x, # Etiquetas
       colors = ["pink", "orange", "red", "darkred"], # Colores
       radius = 2, # Radio del circulo.
       center = (3, 3), # Punto central donde dibujar el circulo.
       wedgeprops = {"linewidth": 1.5, "edgecolor": "white"}, # Estilo del borde
       frame = True # Centrar el gráfico
      )

plt.show()

Matplotlib provee un conjunto de temas que podemos utilizar, algunos de ellos son:

plt.style.use('fivethirtyeight')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('bmh')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('dark_background')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('grayscale')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('classic')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()
plt.style.use('default')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], '-->')
plt.show()

La lista completa de temas es la siguiente:

plt.style.available
['Solarize_Light2',
 '_classic_test_patch',
 '_mpl-gallery',
 '_mpl-gallery-nogrid',
 'bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn-v0_8',
 'seaborn-v0_8-bright',
 'seaborn-v0_8-colorblind',
 'seaborn-v0_8-dark',
 'seaborn-v0_8-dark-palette',
 'seaborn-v0_8-darkgrid',
 'seaborn-v0_8-deep',
 'seaborn-v0_8-muted',
 'seaborn-v0_8-notebook',
 'seaborn-v0_8-paper',
 'seaborn-v0_8-pastel',
 'seaborn-v0_8-poster',
 'seaborn-v0_8-talk',
 'seaborn-v0_8-ticks',
 'seaborn-v0_8-white',
 'seaborn-v0_8-whitegrid',
 'tableau-colorblind10']

La leyenda nos ayuda a identificar elementos en el gráfico. Por tanto, es muy importante saber como utilizarla.

Definir la leyenda

Cuando agregamos varios gráficos podemos agregar el parámetro label para nombrar cada uno de esos gráficos. De esta manera solo tendremos que invocar a la función legend.

etq = ["A", "B", "C", "D", "E"]
x = np.arange(len(etq))
grupo_1 = [2, 5, 2, 1, 4]
grupo_2 = [3, 3, 4, 1, 2]
grupo_3 = [1, 2, 4, 2, 5]

width = 0.25

fig, ax = plt.subplots()

ax.bar(x - width, grupo_1, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 1")
ax.bar(x, grupo_2, width = width, edgecolor = "white", linewidth = 1.5,         label = "Grupo 2")
ax.bar(x + width, grupo_3, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 3")
ax.set_xticks(x, etq)

ax.legend(title = "Grupos")

plt.show()

En ocasiones se puede presentar un solo gráfico, pero que contiene multiples categorías.

y = [1, 2, 3, 4]

# plot
fig, ax = plt.subplots()
circular = ax.pie(y,
       colors = ["pink", "orange", "red", "darkred"], # Colores
       radius = 2, # Radio del circulo.
       center = (3, 3), # Punto central donde dibujar el circulo.
       wedgeprops = {"linewidth": 1.5, "edgecolor": "white"}, # Estilo del borde
       frame = True # Centrar el gráfico
      )

ax.legend(circular, labels = ["A", "B", "C", "D"])

plt.axis('off') # Eliminar ejes
plt.show()
Posicionar la leyenda

Para posicionar la leyenda podemos utilizar el parámetro loc.

loc: Con este parámetro indicamos en que lugar queremos la leyenda, los posibles valores son: ‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center right’, ‘lower center’, ‘upper center’, ‘center’. También puede ser un par ordenado.

Utilizando un valor de posición.

y = [1, 2, 3, 4]

# plot
fig, ax = plt.subplots()
circular = ax.pie(y,
       colors = ["pink", "orange", "red", "darkred"], # Colores
       radius = 2, # Radio del circulo.
       center = (3, 3), # Punto central donde dibujar el circulo.
       wedgeprops = {"linewidth": 1.5, "edgecolor": "white"}, # Estilo del borde
       frame = True # Centrar el gráfico
      )

ax.legend(circular, labels = ["A", "B", "C", "D"], loc = "upper right")

plt.axis('off') # Eliminar ejes
plt.show()

Utilizando un valor de par ordenado.

etq = ["A", "B", "C", "D", "E"]
x = np.arange(len(etq))
grupo_1 = [2, 5, 2, 1, 4]
grupo_2 = [3, 3, 4, 1, 2]
grupo_3 = [1, 2, 4, 2, 5]

width = 0.25

fig, ax = plt.subplots()

ax.bar(x - width, grupo_1, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 1")
ax.bar(x, grupo_2, width = width, edgecolor = "white", linewidth = 1.5,         label = "Grupo 2")
ax.bar(x + width, grupo_3, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 3")
ax.set_xticks(x, etq)

ax.legend(title = "Grupos", loc = (1.05, 0.8))

plt.tight_layout() # Agregar esta instrucción para ajustar el gráfico y la leyenda.
plt.show()

Seleccionar los colores adecuados es muy importante ya que estos pueden ayudar a que el gráfico sea más fácil de interpretar y que sea más llamativo de manera que capte mejor la atención de los espectadores. Por tanto, tener en cuenta lo siguiente:

Definir el color: Para definir el color tenemos varias opciones como utilizar un nombre reservado del color, código hexadecimal o código RGB. Por ejemplo:

x  =  4 + np.random.normal(0, 2, 50)
y1 =  4 + np.random.normal(0, 2, len(x))
y2 = 4 + np.random.normal(0, 2, len(x))
y3 = 4 + np.random.normal(0, 2, len(x))

fig, ax = plt.subplots()

ax.scatter(x, y1, marker = "o", s = 100, c = 'aqua')
ax.scatter(x, y2, marker = "o", s = 100, c = '#D2691E')
ax.scatter(x, y3, marker = "o", s = 100, c = [(0.1, 0.2, 0.5)])

plt.show()

Transparencia del color: Agregar cierta transparencia al color nos permite observar elementos que se sobre-ponen, además en ocasiones nos va a funcionar para bajar la tonalidad del color de manera que sea vea mejor el gráfico.

x  =  4 + np.random.normal(0, 2, 50)
y1 =  4 + np.random.normal(0, 2, len(x))
y2 = 4 + np.random.normal(0, 2, len(x))
y3 = 4 + np.random.normal(0, 2, len(x))

fig, ax = plt.subplots()

ax.scatter(x, y1, marker = "o", s = 100, c = 'aqua', alpha = 0.3)
ax.scatter(x, y2, marker = "o", s = 100, c = '#D2691E', alpha = 0.3)
ax.scatter(x, y3, marker = "o", s = 100, c = [(0.1, 0.2, 0.5)], alpha = 0.6)

plt.show()

Mapas de colores: Matplotlib también provee un conjunto de mapas de colores, estos pueden servir para diferentes propositos, por ejemplo:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm

# Esta función sirve unicamente para mostrar los colores.
cmaps = {}

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(category, cmap_list):
    # Create figure and adjust figure height to number of colormaps
    nrows = len(cmap_list)
    figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22
    fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh))
    fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh,
                        left=0.2, right=0.99)
    axs[0].set_title(f'{category} colormaps', fontsize=14)
    
    for ax, name in zip(axs, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10,
                transform=ax.transAxes)
    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axs:
      ax.set_axis_off()
    # Save colormap list for later.
    cmaps[category] = cmap_list
Secuencias
plot_color_gradients('Secuencias',
                     ['viridis', 'plasma', 'inferno', 'magma', 'cividis'])
plt.show()
plot_color_gradients('Secuencias',
                     ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
                      'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
                      'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'])
plt.show()
plot_color_gradients('Secuencias',
                     ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone',
                      'pink', 'spring', 'summer', 'autumn', 'winter', 'cool',
                      'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'])
plt.show()
Divergentes
plot_color_gradients('Divergentes',
                     ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu',
                      'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'])
plt.show()
Ciclicos
plot_color_gradients('Ciclicos', ['twilight', 'twilight_shifted', 'hsv'])
plt.show()
Cualitativos
plot_color_gradients('Cualitativos',
                     ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',
                      'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',
                      'tab20c'])
plt.show()

En ocasiones se desea agregar una anotación adicional para captar la atención en algún aspecto en espécifico. Para ello, vamos a utilziar el método annotate.

etq = ["A", "B", "C", "D", "E"]
x = np.arange(len(etq))
grupo_1 = [2, 5, 2, 1, 4]
grupo_2 = [3, 3, 4, 1, 2]
grupo_3 = [1, 2, 4, 2, 5]

width = 0.25

fig, ax = plt.subplots()

ax.bar(x - width, grupo_1, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 1")
ax.bar(x, grupo_2, width = width, edgecolor = "white", linewidth = 1.5,         label = "Grupo 2")
ax.bar(x + width, grupo_3, width = width, edgecolor = "white", linewidth = 1.5, label = "Grupo 3")
ax.set_xticks(x, etq)

ax.legend(title = "Grupos", loc = (1.05, 0.7))

ax.annotate(
  "Anotación", xytext = (3, 4.5), # Texto y posición
  xy = (2, 4), # Punto inicial para la flecha
  xycoords = 'data', textcoords = 'data', # Utilizar los valores de los datos como las coordenadas
  arrowprops = dict(arrowstyle = "->", connectionstyle = "arc3") # Dibujar una flecha
)

plt.tight_layout() # Agregar esta instrucción para ajustar el gráfico y la leyenda.
plt.show()
Text(3, 4.5, 'Anotación')

Cuando definimos un gráfico con subplot podemos indicar, similar como con una matriz, la cantidad de filas y columnas en las que queremos dividir la figura, de manera tal que podemos añadir un gráfico diferente a cada una de esas divisiones. Por ejemplo:

x  = 4 + np.random.normal(0, 2, 50)
y1 = 4 + np.random.normal(0, 2, len(x))
y2 = 4 + np.random.normal(0, 2, len(x))
y3 = 4 + np.random.normal(0, 2, len(x))

fig, axs = plt.subplots(3, 1)

no_print = axs[0].scatter(x, y1, marker = "o", s = 100, c = 'aqua', alpha = 0.3)
no_print = axs[0].axes.xaxis.set_ticklabels([])
no_print = axs[1].scatter(x, y2, marker = "o", s = 100, c = 'red', alpha = 0.3)
no_print = axs[1].axes.xaxis.set_ticklabels([])
no_print = axs[2].scatter(x, y3, marker = "o", s = 100, c = 'blue', alpha = 0.6)

plt.show()
x  = 4 + np.random.normal(0, 2, 50)
y1 = 4 + np.random.normal(0, 2, len(x))
y2 = 4 + np.random.normal(0, 2, len(x))
y3 = 4 + np.random.normal(0, 2, len(x))
y4 = 4 + np.random.normal(0, 2, len(x))

fig, axs = plt.subplots(2, 2)

no_print = axs[0, 0].scatter(x, y1, marker = "o", s = 100, alpha = 0.3, label = "y1", c = 'aqua')
no_print = axs[1, 0].scatter(x, y2, marker = "d", s = 100, alpha = 0.3, label = "y2", c = 'red')
no_print = axs[0, 1].scatter(x, y2, marker = "s", s = 100, alpha = 0.3, label = "y3", c = 'blue')
no_print = axs[1, 1].scatter(x, y2, marker = "+", s = 100, alpha = 0.3, label = "y4", c = 'green')

plt.show()

El paquete seaborn es otra librería de visualización que se basa en Matplotlib. Esta librería depende de Matplotlib y en ocasiones utiliza varios de los componentes de Matplotlib para realizar gráficos.

pip install seaborn

Una vez instalado podemos empezar a usarlo cargandolo de la siguiente manera:

import seaborn as sns

plt.style.use('seaborn-v0_8')

Para mayor información del paquete puede visitar el siguiente enlace: https://seaborn.pydata.org/index.html

fig, ax = plt.subplots()
sns.lineplot(x = range(150), y = iris.s_largo, hue = iris.tipo, ax = ax)
ax.legend(loc = "upper left")
plt.show()
fig, ax = plt.subplots()
sns.scatterplot(x = iris.s_ancho, y = iris.s_largo, hue = iris.tipo, 
                size = iris.p_ancho, alpha = 0.6, ax = ax)
ax.legend(loc = "upper right")
plt.show()
tam_s_largo = ["ancho" if x > 3 else "angosto" for x in iris.s_ancho]

fig, ax = plt.subplots()
sns.barplot(x = iris.tipo, y = iris.s_largo, hue = tam_s_largo, ax = ax)
ax.legend(loc = "upper left")
plt.show()
fig, ax = plt.subplots()
sns.histplot(x = iris.s_ancho, ax = ax)
plt.show()
fig, ax = plt.subplots()
sns.boxplot(x = iris.s_ancho, ax = ax)
plt.show()
corr = iris.iloc[:, 0:4].corr()

fig, ax = plt.subplots()
sns.heatmap(corr, annot = True, vmin = -1, vmax = 1, cmap = 'RdBu', ax = ax)
plt.show()
sns.pairplot(iris, hue = "tipo")